package jju.edu.mvptest.presenter;

import android.os.Handler;
import android.os.Message;

import java.util.ArrayList;
import java.util.Random;

import jju.edu.mvptest.model.Phone;
import jju.edu.mvptest.model.Phonefactory;
import jju.edu.mvptest.view.OperationView;

/**
 * Created by Administrator on 2016/12/1.
 */

public class PhonePresenter implements TaskPresenter{
        private final Phonefactory mPhonefactory ;
        private final OperationView mOperationView ;

        public static final long createPhoneTime = 2000;
        public static final int msgWhat = 123;
        public PhonePresenter( OperationView view) {
            this.mPhonefactory = new Phonefactory();
            this.mOperationView = view;
        }

        @Override
        public void addPhone(Phone phone) {
            mOperationView.showPhoneCountChange();
            if(mHandler.hasMessages(msgWhat)){
                mOperationView.showFactoryBusy();
            }
            Message msg = new Message();
            msg.what = msgWhat;
            msg.obj = phone;
            mHandler.sendMessageDelayed(msg,createPhoneTime);
            mOperationView.showCreatingPhone();
        }
    @Override
    public void addRandomPhone() {
        addPhone(new Phone("iphone", 4000 + new Random().nextInt(1000)));
    }
        private Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == msgWhat){
                    mPhonefactory.addPhone((Phone) msg.obj);
                    mOperationView.showPhoneCountChange();
                    mOperationView.showCreatedPhone();
                }
            }
        };
        @Override
        public void removePhone(int index) {
           mPhonefactory.removePhone(index);

        }

        @Override
        public ArrayList<Phone> getPhonesList(){
            ArrayList<Phone> olist = mPhonefactory.getOlist();
            return olist;
        }
}
